home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / rfc822.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  30.1 KB  |  1,154 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """RFC 2822 message manipulation.
  5.  
  6. Note: This is only a very rough sketch of a full RFC-822 parser; in particular
  7. the tokenizing of addresses does not adhere to all the quoting rules.
  8.  
  9. Note: RFC 2822 is a long awaited update to RFC 822.  This module should
  10. conform to RFC 2822, and is thus mis-named (it's not worth renaming it).  Some
  11. effort at RFC 2822 updates have been made, but a thorough audit has not been
  12. performed.  Consider any RFC 2822 non-conformance to be a bug.
  13.  
  14.     RFC 2822: http://www.faqs.org/rfcs/rfc2822.html
  15.     RFC 822 : http://www.faqs.org/rfcs/rfc822.html (obsolete)
  16.  
  17. Directions for use:
  18.  
  19. To create a Message object: first open a file, e.g.:
  20.  
  21.   fp = open(file, 'r')
  22.  
  23. You can use any other legal way of getting an open file object, e.g. use
  24. sys.stdin or call os.popen().  Then pass the open file object to the Message()
  25. constructor:
  26.  
  27.   m = Message(fp)
  28.  
  29. This class can work with any input object that supports a readline method.  If
  30. the input object has seek and tell capability, the rewindbody method will
  31. work; also illegal lines will be pushed back onto the input stream.  If the
  32. input object lacks seek but has an `unread' method that can push back a line
  33. of input, Message will use that to push back illegal lines.  Thus this class
  34. can be used to parse messages coming from a buffered stream.
  35.  
  36. The optional `seekable' argument is provided as a workaround for certain stdio
  37. libraries in which tell() discards buffered data before discovering that the
  38. lseek() system call doesn't work.  For maximum portability, you should set the
  39. seekable argument to zero to prevent that initial \\code{tell} when passing in
  40. an unseekable object such as a a file object created from a socket object.  If
  41. it is 1 on entry -- which it is by default -- the tell() method of the open
  42. file object is called once; if this raises an exception, seekable is reset to
  43. 0.  For other nonzero values of seekable, this test is not made.
  44.  
  45. To get the text of a particular header there are several methods:
  46.  
  47.   str = m.getheader(name)
  48.   str = m.getrawheader(name)
  49.  
  50. where name is the name of the header, e.g. 'Subject'.  The difference is that
  51. getheader() strips the leading and trailing whitespace, while getrawheader()
  52. doesn't.  Both functions retain embedded whitespace (including newlines)
  53. exactly as they are specified in the header, and leave the case of the text
  54. unchanged.
  55.  
  56. For addresses and address lists there are functions
  57.  
  58.   realname, mailaddress = m.getaddr(name)
  59.   list = m.getaddrlist(name)
  60.  
  61. where the latter returns a list of (realname, mailaddr) tuples.
  62.  
  63. There is also a method
  64.  
  65.   time = m.getdate(name)
  66.  
  67. which parses a Date-like field and returns a time-compatible tuple,
  68. i.e. a tuple such as returned by time.localtime() or accepted by
  69. time.mktime().
  70.  
  71. See the class definition for lower level access methods.
  72.  
  73. There are also some utility functions here.
  74. """
  75. import time
  76. __all__ = [
  77.     'Message',
  78.     'AddressList',
  79.     'parsedate',
  80.     'parsedate_tz',
  81.     'mktime_tz']
  82. _blanklines = ('\r\n', '\n')
  83.  
  84. class Message:
  85.     '''Represents a single RFC 2822-compliant message.'''
  86.     
  87.     def __init__(self, fp, seekable = 1):
  88.         '''Initialize the class instance and read the headers.'''
  89.         if seekable == 1:
  90.             
  91.             try:
  92.                 fp.tell()
  93.             except (AttributeError, IOError):
  94.                 seekable = 0
  95.             except:
  96.                 None<EXCEPTION MATCH>(AttributeError, IOError)
  97.             
  98.  
  99.         None<EXCEPTION MATCH>(AttributeError, IOError)
  100.         self.fp = fp
  101.         self.seekable = seekable
  102.         self.startofheaders = None
  103.         self.startofbody = None
  104.         if self.seekable:
  105.             
  106.             try:
  107.                 self.startofheaders = self.fp.tell()
  108.             except IOError:
  109.                 self.seekable = 0
  110.             except:
  111.                 None<EXCEPTION MATCH>IOError
  112.             
  113.  
  114.         None<EXCEPTION MATCH>IOError
  115.         self.readheaders()
  116.         if self.seekable:
  117.             
  118.             try:
  119.                 self.startofbody = self.fp.tell()
  120.             except IOError:
  121.                 self.seekable = 0
  122.             except:
  123.                 None<EXCEPTION MATCH>IOError
  124.             
  125.  
  126.         None<EXCEPTION MATCH>IOError
  127.  
  128.     
  129.     def rewindbody(self):
  130.         '''Rewind the file to the start of the body (if seekable).'''
  131.         if not self.seekable:
  132.             raise IOError, 'unseekable file'
  133.         
  134.         self.fp.seek(self.startofbody)
  135.  
  136.     
  137.     def readheaders(self):
  138.         '''Read header lines.
  139.  
  140.         Read header lines up to the entirely blank line that terminates them.
  141.         The (normally blank) line that ends the headers is skipped, but not
  142.         included in the returned list.  If a non-header line ends the headers,
  143.         (which is an error), an attempt is made to backspace over it; it is
  144.         never included in the returned list.
  145.  
  146.         The variable self.status is set to the empty string if all went well,
  147.         otherwise it is an error message.  The variable self.headers is a
  148.         completely uninterpreted list of lines contained in the header (so
  149.         printing them will reproduce the header exactly as it appears in the
  150.         file).
  151.         '''
  152.         self.dict = { }
  153.         self.unixfrom = ''
  154.         self.headers = lst = []
  155.         self.status = ''
  156.         headerseen = ''
  157.         firstline = 1
  158.         startofline = None
  159.         unread = None
  160.         tell = None
  161.         if hasattr(self.fp, 'unread'):
  162.             unread = self.fp.unread
  163.         elif self.seekable:
  164.             tell = self.fp.tell
  165.         
  166.         while tell:
  167.             
  168.             try:
  169.                 startofline = tell()
  170.             except IOError:
  171.                 startofline = None
  172.                 tell = None
  173.                 self.seekable = 0
  174.             except:
  175.                 None<EXCEPTION MATCH>IOError
  176.             
  177.  
  178.             None<EXCEPTION MATCH>IOError
  179.             line = self.fp.readline()
  180.             if not line:
  181.                 self.status = 'EOF in headers'
  182.                 break
  183.             
  184.         if firstline and line.startswith('From '):
  185.             self.unixfrom = self.unixfrom + line
  186.             continue
  187.         
  188.         firstline = 0
  189.         if headerseen and line[0] in ' \t':
  190.             lst.append(line)
  191.             x = self.dict[headerseen] + '\n ' + line.strip()
  192.             self.dict[headerseen] = x.strip()
  193.             continue
  194.         elif self.iscomment(line):
  195.             continue
  196.         elif self.islast(line):
  197.             break
  198.         
  199.         headerseen = self.isheader(line)
  200.         if headerseen:
  201.             lst.append(line)
  202.             self.dict[headerseen] = line[len(headerseen) + 1:].strip()
  203.             continue
  204.             continue
  205.         if not self.dict:
  206.             self.status = 'No headers'
  207.         else:
  208.             self.status = 'Non-header line where header expected'
  209.         if unread:
  210.             unread(line)
  211.         elif tell:
  212.             self.fp.seek(startofline)
  213.         else:
  214.             self.status = self.status + '; bad seek'
  215.         break
  216.         continue
  217.  
  218.     
  219.     def isheader(self, line):
  220.         '''Determine whether a given line is a legal header.
  221.  
  222.         This method should return the header name, suitably canonicalized.
  223.         You may override this method in order to use Message parsing on tagged
  224.         data in RFC 2822-like formats with special header formats.
  225.         '''
  226.         i = line.find(':')
  227.         if i > 0:
  228.             return line[:i].lower()
  229.         
  230.         return None
  231.  
  232.     
  233.     def islast(self, line):
  234.         """Determine whether a line is a legal end of RFC 2822 headers.
  235.  
  236.         You may override this method if your application wants to bend the
  237.         rules, e.g. to strip trailing whitespace, or to recognize MH template
  238.         separators ('--------').  For convenience (e.g. for code reading from
  239.         sockets) a line consisting of \r
  240.  also matches.
  241.         """
  242.         return line in _blanklines
  243.  
  244.     
  245.     def iscomment(self, line):
  246.         '''Determine whether a line should be skipped entirely.
  247.  
  248.         You may override this method in order to use Message parsing on tagged
  249.         data in RFC 2822-like formats that support embedded comments or
  250.         free-text data.
  251.         '''
  252.         return False
  253.  
  254.     
  255.     def getallmatchingheaders(self, name):
  256.         '''Find all header lines matching a given header name.
  257.  
  258.         Look through the list of headers and find all lines matching a given
  259.         header name (and their continuation lines).  A list of the lines is
  260.         returned, without interpretation.  If the header does not occur, an
  261.         empty list is returned.  If the header occurs multiple times, all
  262.         occurrences are returned.  Case is not important in the header name.
  263.         '''
  264.         name = name.lower() + ':'
  265.         n = len(name)
  266.         lst = []
  267.         hit = 0
  268.         for line in self.headers:
  269.             if line[:n].lower() == name:
  270.                 hit = 1
  271.             elif not line[:1].isspace():
  272.                 hit = 0
  273.             
  274.             if hit:
  275.                 lst.append(line)
  276.                 continue
  277.         
  278.         return lst
  279.  
  280.     
  281.     def getfirstmatchingheader(self, name):
  282.         '''Get the first header line matching name.
  283.  
  284.         This is similar to getallmatchingheaders, but it returns only the
  285.         first matching header (and its continuation lines).
  286.         '''
  287.         name = name.lower() + ':'
  288.         n = len(name)
  289.         lst = []
  290.         hit = 0
  291.         for line in self.headers:
  292.             if hit:
  293.                 if not line[:1].isspace():
  294.                     break
  295.                 
  296.             elif line[:n].lower() == name:
  297.                 hit = 1
  298.             
  299.             if hit:
  300.                 lst.append(line)
  301.                 continue
  302.         
  303.         return lst
  304.  
  305.     
  306.     def getrawheader(self, name):
  307.         '''A higher-level interface to getfirstmatchingheader().
  308.  
  309.         Return a string containing the literal text of the header but with the
  310.         keyword stripped.  All leading, trailing and embedded whitespace is
  311.         kept in the string, however.  Return None if the header does not
  312.         occur.
  313.         '''
  314.         lst = self.getfirstmatchingheader(name)
  315.         if not lst:
  316.             return None
  317.         
  318.         lst[0] = lst[0][len(name) + 1:]
  319.         return ''.join(lst)
  320.  
  321.     
  322.     def getheader(self, name, default = None):
  323.         """Get the header value for a name.
  324.  
  325.         This is the normal interface: it returns a stripped version of the
  326.         header value for a given header name, or None if it doesn't exist.
  327.         This uses the dictionary version which finds the *last* such header.
  328.         """
  329.         return self.dict.get(name.lower(), default)
  330.  
  331.     get = getheader
  332.     
  333.     def getheaders(self, name):
  334.         '''Get all values for a header.
  335.  
  336.         This returns a list of values for headers given more than once; each
  337.         value in the result list is stripped in the same way as the result of
  338.         getheader().  If the header is not given, return an empty list.
  339.         '''
  340.         result = []
  341.         current = ''
  342.         have_header = 0
  343.         for s in self.getallmatchingheaders(name):
  344.             if s[0].isspace():
  345.                 if current:
  346.                     current = '%s\n %s' % (current, s.strip())
  347.                 else:
  348.                     current = s.strip()
  349.             current
  350.             if have_header:
  351.                 result.append(current)
  352.             
  353.             current = s[s.find(':') + 1:].strip()
  354.             have_header = 1
  355.         
  356.         if have_header:
  357.             result.append(current)
  358.         
  359.         return result
  360.  
  361.     
  362.     def getaddr(self, name):
  363.         """Get a single address from a header, as a tuple.
  364.  
  365.         An example return value:
  366.         ('Guido van Rossum', 'guido@cwi.nl')
  367.         """
  368.         alist = self.getaddrlist(name)
  369.         if alist:
  370.             return alist[0]
  371.         else:
  372.             return (None, None)
  373.  
  374.     
  375.     def getaddrlist(self, name):
  376.         '''Get a list of addresses from a header.
  377.  
  378.         Retrieves a list of addresses from a header, where each address is a
  379.         tuple as returned by getaddr().  Scans all named headers, so it works
  380.         properly with multiple To: or Cc: headers for example.
  381.         '''
  382.         raw = []
  383.         for h in self.getallmatchingheaders(name):
  384.             if h[0] in ' \t':
  385.                 raw.append(h)
  386.                 continue
  387.             if raw:
  388.                 raw.append(', ')
  389.             
  390.             i = h.find(':')
  391.             if i > 0:
  392.                 addr = h[i + 1:]
  393.             
  394.             raw.append(addr)
  395.         
  396.         alladdrs = ''.join(raw)
  397.         a = AddressList(alladdrs)
  398.         return a.addresslist
  399.  
  400.     
  401.     def getdate(self, name):
  402.         '''Retrieve a date field from a header.
  403.  
  404.         Retrieves a date field from the named header, returning a tuple
  405.         compatible with time.mktime().
  406.         '''
  407.         
  408.         try:
  409.             data = self[name]
  410.         except KeyError:
  411.             return None
  412.  
  413.         return parsedate(data)
  414.  
  415.     
  416.     def getdate_tz(self, name):
  417.         """Retrieve a date field from a header as a 10-tuple.
  418.  
  419.         The first 9 elements make up a tuple compatible with time.mktime(),
  420.         and the 10th is the offset of the poster's time zone from GMT/UTC.
  421.         """
  422.         
  423.         try:
  424.             data = self[name]
  425.         except KeyError:
  426.             return None
  427.  
  428.         return parsedate_tz(data)
  429.  
  430.     
  431.     def __len__(self):
  432.         '''Get the number of headers in a message.'''
  433.         return len(self.dict)
  434.  
  435.     
  436.     def __getitem__(self, name):
  437.         '''Get a specific header, as from a dictionary.'''
  438.         return self.dict[name.lower()]
  439.  
  440.     
  441.     def __setitem__(self, name, value):
  442.         '''Set the value of a header.
  443.  
  444.         Note: This is not a perfect inversion of __getitem__, because any
  445.         changed headers get stuck at the end of the raw-headers list rather
  446.         than where the altered header was.
  447.         '''
  448.         del self[name]
  449.         self.dict[name.lower()] = value
  450.         text = name + ': ' + value
  451.         for line in text.split('\n'):
  452.             self.headers.append(line + '\n')
  453.         
  454.  
  455.     
  456.     def __delitem__(self, name):
  457.         '''Delete all occurrences of a specific header, if it is present.'''
  458.         name = name.lower()
  459.         if name not in self.dict:
  460.             return None
  461.         
  462.         del self.dict[name]
  463.         name = name + ':'
  464.         n = len(name)
  465.         lst = []
  466.         hit = 0
  467.         for i in range(len(self.headers)):
  468.             line = self.headers[i]
  469.             if line[:n].lower() == name:
  470.                 hit = 1
  471.             elif not line[:1].isspace():
  472.                 hit = 0
  473.             
  474.             if hit:
  475.                 lst.append(i)
  476.                 continue
  477.         
  478.         for i in reversed(lst):
  479.             del self.headers[i]
  480.         
  481.  
  482.     
  483.     def setdefault(self, name, default = ''):
  484.         lowername = name.lower()
  485.         if lowername in self.dict:
  486.             return self.dict[lowername]
  487.         else:
  488.             text = name + ': ' + default
  489.             for line in text.split('\n'):
  490.                 self.headers.append(line + '\n')
  491.             
  492.             self.dict[lowername] = default
  493.             return default
  494.  
  495.     
  496.     def has_key(self, name):
  497.         '''Determine whether a message contains the named header.'''
  498.         return name.lower() in self.dict
  499.  
  500.     
  501.     def __contains__(self, name):
  502.         '''Determine whether a message contains the named header.'''
  503.         return name.lower() in self.dict
  504.  
  505.     
  506.     def __iter__(self):
  507.         return iter(self.dict)
  508.  
  509.     
  510.     def keys(self):
  511.         """Get all of a message's header field names."""
  512.         return self.dict.keys()
  513.  
  514.     
  515.     def values(self):
  516.         """Get all of a message's header field values."""
  517.         return self.dict.values()
  518.  
  519.     
  520.     def items(self):
  521.         """Get all of a message's headers.
  522.  
  523.         Returns a list of name, value tuples.
  524.         """
  525.         return self.dict.items()
  526.  
  527.     
  528.     def __str__(self):
  529.         return ''.join(self.headers)
  530.  
  531.  
  532.  
  533. def unquote(s):
  534.     '''Remove quotes from a string.'''
  535.     if len(s) > 1:
  536.         if s.startswith('"') and s.endswith('"'):
  537.             return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  538.         
  539.         if s.startswith('<') and s.endswith('>'):
  540.             return s[1:-1]
  541.         
  542.     
  543.     return s
  544.  
  545.  
  546. def quote(s):
  547.     '''Add quotes around a string.'''
  548.     return s.replace('\\', '\\\\').replace('"', '\\"')
  549.  
  550.  
  551. def parseaddr(address):
  552.     '''Parse an address into a (realname, mailaddr) tuple.'''
  553.     a = AddressList(address)
  554.     lst = a.addresslist
  555.     if not lst:
  556.         return (None, None)
  557.     
  558.     return lst[0]
  559.  
  560.  
  561. class AddrlistClass:
  562.     '''Address parser class by Ben Escoto.
  563.  
  564.     To understand what this class does, it helps to have a copy of
  565.     RFC 2822 in front of you.
  566.  
  567.     http://www.faqs.org/rfcs/rfc2822.html
  568.  
  569.     Note: this class interface is deprecated and may be removed in the future.
  570.     Use rfc822.AddressList instead.
  571.     '''
  572.     
  573.     def __init__(self, field):
  574.         """Initialize a new instance.
  575.  
  576.         `field' is an unparsed address header field, containing one or more
  577.         addresses.
  578.         """
  579.         self.specials = '()<>@,:;."[]'
  580.         self.pos = 0
  581.         self.LWS = ' \t'
  582.         self.CR = '\r\n'
  583.         self.atomends = self.specials + self.LWS + self.CR
  584.         self.phraseends = self.atomends.replace('.', '')
  585.         self.field = field
  586.         self.commentlist = []
  587.  
  588.     
  589.     def gotonext(self):
  590.         '''Parse up to the start of the next address.'''
  591.         while self.pos < len(self.field):
  592.             if self.field[self.pos] in self.LWS + '\n\r':
  593.                 self.pos = self.pos + 1
  594.                 continue
  595.             if self.field[self.pos] == '(':
  596.                 self.commentlist.append(self.getcomment())
  597.                 continue
  598.             break
  599.  
  600.     
  601.     def getaddrlist(self):
  602.         '''Parse all addresses.
  603.  
  604.         Returns a list containing all of the addresses.
  605.         '''
  606.         result = []
  607.         ad = self.getaddress()
  608.         while ad:
  609.             result += ad
  610.             ad = self.getaddress()
  611.         return result
  612.  
  613.     
  614.     def getaddress(self):
  615.         '''Parse the next address.'''
  616.         self.commentlist = []
  617.         self.gotonext()
  618.         oldpos = self.pos
  619.         oldcl = self.commentlist
  620.         plist = self.getphraselist()
  621.         self.gotonext()
  622.         returnlist = []
  623.         if self.pos >= len(self.field):
  624.             if plist:
  625.                 returnlist = [
  626.                     (' '.join(self.commentlist), plist[0])]
  627.             
  628.         elif self.field[self.pos] in '.@':
  629.             self.pos = oldpos
  630.             self.commentlist = oldcl
  631.             addrspec = self.getaddrspec()
  632.             returnlist = [
  633.                 (' '.join(self.commentlist), addrspec)]
  634.         elif self.field[self.pos] == ':':
  635.             returnlist = []
  636.             fieldlen = len(self.field)
  637.             self.pos += 1
  638.             while self.pos < len(self.field):
  639.                 self.gotonext()
  640.                 returnlist = returnlist + self.getaddress()
  641.                 continue
  642.                 None if self.pos < fieldlen and self.field[self.pos] == ';' else self
  643.         elif self.field[self.pos] == '<':
  644.             routeaddr = self.getrouteaddr()
  645.             if self.commentlist:
  646.                 returnlist = [
  647.                     (' '.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)]
  648.             else:
  649.                 returnlist = [
  650.                     (' '.join(plist), routeaddr)]
  651.         elif plist:
  652.             returnlist = [
  653.                 (' '.join(self.commentlist), plist[0])]
  654.         elif self.field[self.pos] in self.specials:
  655.             self.pos += 1
  656.         
  657.         self.gotonext()
  658.         if self.pos < len(self.field) and self.field[self.pos] == ',':
  659.             self.pos += 1
  660.         
  661.         return returnlist
  662.  
  663.     
  664.     def getrouteaddr(self):
  665.         '''Parse a route address (Return-path value).
  666.  
  667.         This method just skips all the route stuff and returns the addrspec.
  668.         '''
  669.         if self.field[self.pos] != '<':
  670.             return None
  671.         
  672.         expectroute = 0
  673.         self.pos += 1
  674.         self.gotonext()
  675.         adlist = ''
  676.         while self.pos < len(self.field):
  677.             if expectroute:
  678.                 self.getdomain()
  679.                 expectroute = 0
  680.             elif self.field[self.pos] == '>':
  681.                 self.pos += 1
  682.                 break
  683.             elif self.field[self.pos] == '@':
  684.                 self.pos += 1
  685.                 expectroute = 1
  686.             elif self.field[self.pos] == ':':
  687.                 self.pos += 1
  688.             else:
  689.                 adlist = self.getaddrspec()
  690.                 self.pos += 1
  691.                 break
  692.             self.gotonext()
  693.             continue
  694.             self
  695.         return adlist
  696.  
  697.     
  698.     def getaddrspec(self):
  699.         '''Parse an RFC 2822 addr-spec.'''
  700.         aslist = []
  701.         self.gotonext()
  702.         while self.pos < len(self.field):
  703.             if self.field[self.pos] == '.':
  704.                 aslist.append('.')
  705.                 self.pos += 1
  706.             elif self.field[self.pos] == '"':
  707.                 aslist.append('"%s"' % self.getquote())
  708.             elif self.field[self.pos] in self.atomends:
  709.                 break
  710.             else:
  711.                 aslist.append(self.getatom())
  712.             self.gotonext()
  713.         if self.pos >= len(self.field) or self.field[self.pos] != '@':
  714.             return ''.join(aslist)
  715.         
  716.         aslist.append('@')
  717.         self.pos += 1
  718.         self.gotonext()
  719.         return ''.join(aslist) + self.getdomain()
  720.  
  721.     
  722.     def getdomain(self):
  723.         '''Get the complete domain name from an address.'''
  724.         sdlist = []
  725.         while self.pos < len(self.field):
  726.             if self.field[self.pos] in self.LWS:
  727.                 self.pos += 1
  728.                 continue
  729.             self
  730.             if self.field[self.pos] == '(':
  731.                 self.commentlist.append(self.getcomment())
  732.                 continue
  733.             if self.field[self.pos] == '[':
  734.                 sdlist.append(self.getdomainliteral())
  735.                 continue
  736.             if self.field[self.pos] == '.':
  737.                 self.pos += 1
  738.                 sdlist.append('.')
  739.                 continue
  740.             self
  741.             if self.field[self.pos] in self.atomends:
  742.                 break
  743.                 continue
  744.             sdlist.append(self.getatom())
  745.         return ''.join(sdlist)
  746.  
  747.     
  748.     def getdelimited(self, beginchar, endchars, allowcomments = 1):
  749.         """Parse a header fragment delimited by special characters.
  750.  
  751.         `beginchar' is the start character for the fragment.  If self is not
  752.         looking at an instance of `beginchar' then getdelimited returns the
  753.         empty string.
  754.  
  755.         `endchars' is a sequence of allowable end-delimiting characters.
  756.         Parsing stops when one of these is encountered.
  757.  
  758.         If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
  759.         within the parsed fragment.
  760.         """
  761.         if self.field[self.pos] != beginchar:
  762.             return ''
  763.         
  764.         slist = [
  765.             '']
  766.         quote = 0
  767.         self.pos += 1
  768.         while self.pos < len(self.field):
  769.             if quote == 1:
  770.                 slist.append(self.field[self.pos])
  771.                 quote = 0
  772.             elif self.field[self.pos] in endchars:
  773.                 self.pos += 1
  774.                 break
  775.             elif allowcomments and self.field[self.pos] == '(':
  776.                 slist.append(self.getcomment())
  777.                 continue
  778.             elif self.field[self.pos] == '\\':
  779.                 quote = 1
  780.             else:
  781.                 slist.append(self.field[self.pos])
  782.             self.pos += 1
  783.             continue
  784.             self
  785.         return ''.join(slist)
  786.  
  787.     
  788.     def getquote(self):
  789.         """Get a quote-delimited fragment from self's field."""
  790.         return self.getdelimited('"', '"\r', 0)
  791.  
  792.     
  793.     def getcomment(self):
  794.         """Get a parenthesis-delimited fragment from self's field."""
  795.         return self.getdelimited('(', ')\r', 1)
  796.  
  797.     
  798.     def getdomainliteral(self):
  799.         '''Parse an RFC 2822 domain-literal.'''
  800.         return '[%s]' % self.getdelimited('[', ']\r', 0)
  801.  
  802.     
  803.     def getatom(self, atomends = None):
  804.         """Parse an RFC 2822 atom.
  805.  
  806.         Optional atomends specifies a different set of end token delimiters
  807.         (the default is to use self.atomends).  This is used e.g. in
  808.         getphraselist() since phrase endings must not include the `.' (which
  809.         is legal in phrases)."""
  810.         atomlist = [
  811.             '']
  812.         if atomends is None:
  813.             atomends = self.atomends
  814.         
  815.         while self.pos < len(self.field):
  816.             if self.field[self.pos] in atomends:
  817.                 break
  818.             else:
  819.                 atomlist.append(self.field[self.pos])
  820.             self.pos += 1
  821.             continue
  822.             self
  823.         return ''.join(atomlist)
  824.  
  825.     
  826.     def getphraselist(self):
  827.         '''Parse a sequence of RFC 2822 phrases.
  828.  
  829.         A phrase is a sequence of words, which are in turn either RFC 2822
  830.         atoms or quoted-strings.  Phrases are canonicalized by squeezing all
  831.         runs of continuous whitespace into one space.
  832.         '''
  833.         plist = []
  834.         while self.pos < len(self.field):
  835.             if self.field[self.pos] in self.LWS:
  836.                 self.pos += 1
  837.                 continue
  838.             self
  839.             if self.field[self.pos] == '"':
  840.                 plist.append(self.getquote())
  841.                 continue
  842.             if self.field[self.pos] == '(':
  843.                 self.commentlist.append(self.getcomment())
  844.                 continue
  845.             if self.field[self.pos] in self.phraseends:
  846.                 break
  847.                 continue
  848.             plist.append(self.getatom(self.phraseends))
  849.         return plist
  850.  
  851.  
  852.  
  853. class AddressList(AddrlistClass):
  854.     '''An AddressList encapsulates a list of parsed RFC 2822 addresses.'''
  855.     
  856.     def __init__(self, field):
  857.         AddrlistClass.__init__(self, field)
  858.         if field:
  859.             self.addresslist = self.getaddrlist()
  860.         else:
  861.             self.addresslist = []
  862.  
  863.     
  864.     def __len__(self):
  865.         return len(self.addresslist)
  866.  
  867.     
  868.     def __str__(self):
  869.         return ', '.join(map(dump_address_pair, self.addresslist))
  870.  
  871.     
  872.     def __add__(self, other):
  873.         newaddr = AddressList(None)
  874.         newaddr.addresslist = self.addresslist[:]
  875.         for x in other.addresslist:
  876.             if x not in self.addresslist:
  877.                 newaddr.addresslist.append(x)
  878.                 continue
  879.         
  880.         return newaddr
  881.  
  882.     
  883.     def __iadd__(self, other):
  884.         for x in other.addresslist:
  885.             if x not in self.addresslist:
  886.                 self.addresslist.append(x)
  887.                 continue
  888.         
  889.         return self
  890.  
  891.     
  892.     def __sub__(self, other):
  893.         newaddr = AddressList(None)
  894.         for x in self.addresslist:
  895.             if x not in other.addresslist:
  896.                 newaddr.addresslist.append(x)
  897.                 continue
  898.         
  899.         return newaddr
  900.  
  901.     
  902.     def __isub__(self, other):
  903.         for x in other.addresslist:
  904.             if x in self.addresslist:
  905.                 self.addresslist.remove(x)
  906.                 continue
  907.         
  908.         return self
  909.  
  910.     
  911.     def __getitem__(self, index):
  912.         return self.addresslist[index]
  913.  
  914.  
  915.  
  916. def dump_address_pair(pair):
  917.     '''Dump a (name, address) pair in a canonicalized form.'''
  918.     if pair[0]:
  919.         return '"' + pair[0] + '" <' + pair[1] + '>'
  920.     else:
  921.         return pair[1]
  922.  
  923. _monthnames = [
  924.     'jan',
  925.     'feb',
  926.     'mar',
  927.     'apr',
  928.     'may',
  929.     'jun',
  930.     'jul',
  931.     'aug',
  932.     'sep',
  933.     'oct',
  934.     'nov',
  935.     'dec',
  936.     'january',
  937.     'february',
  938.     'march',
  939.     'april',
  940.     'may',
  941.     'june',
  942.     'july',
  943.     'august',
  944.     'september',
  945.     'october',
  946.     'november',
  947.     'december']
  948. _daynames = [
  949.     'mon',
  950.     'tue',
  951.     'wed',
  952.     'thu',
  953.     'fri',
  954.     'sat',
  955.     'sun']
  956. _timezones = {
  957.     'UT': 0,
  958.     'UTC': 0,
  959.     'GMT': 0,
  960.     'Z': 0,
  961.     'AST': -400,
  962.     'ADT': -300,
  963.     'EST': -500,
  964.     'EDT': -400,
  965.     'CST': -600,
  966.     'CDT': -500,
  967.     'MST': -700,
  968.     'MDT': -600,
  969.     'PST': -800,
  970.     'PDT': -700 }
  971.  
  972. def parsedate_tz(data):
  973.     '''Convert a date string to a time tuple.
  974.  
  975.     Accounts for military timezones.
  976.     '''
  977.     if not data:
  978.         return None
  979.     
  980.     data = data.split()
  981.     if data[0][-1] in (',', '.') or data[0].lower() in _daynames:
  982.         del data[0]
  983.     
  984.     if len(data) == 3:
  985.         stuff = data[0].split('-')
  986.         if len(stuff) == 3:
  987.             data = stuff + data[1:]
  988.         
  989.     
  990.     if len(data) == 4:
  991.         s = data[3]
  992.         i = s.find('+')
  993.         if i > 0:
  994.             data[3:] = [
  995.                 s[:i],
  996.                 s[i + 1:]]
  997.         else:
  998.             data.append('')
  999.     
  1000.     if len(data) < 5:
  1001.         return None
  1002.     
  1003.     data = data[:5]
  1004.     (dd, mm, yy, tm, tz) = data
  1005.     mm = mm.lower()
  1006.     if mm not in _monthnames:
  1007.         dd = mm
  1008.         mm = dd.lower()
  1009.         if mm not in _monthnames:
  1010.             return None
  1011.         
  1012.     
  1013.     mm = _monthnames.index(mm) + 1
  1014.     if mm > 12:
  1015.         mm = mm - 12
  1016.     
  1017.     if dd[-1] == ',':
  1018.         dd = dd[:-1]
  1019.     
  1020.     i = yy.find(':')
  1021.     if i > 0:
  1022.         yy = tm
  1023.         tm = yy
  1024.     
  1025.     if yy[-1] == ',':
  1026.         yy = yy[:-1]
  1027.     
  1028.     if not yy[0].isdigit():
  1029.         yy = tz
  1030.         tz = yy
  1031.     
  1032.     if tm[-1] == ',':
  1033.         tm = tm[:-1]
  1034.     
  1035.     tm = tm.split(':')
  1036.     if len(tm) == 2:
  1037.         (thh, tmm) = tm
  1038.         tss = '0'
  1039.     elif len(tm) == 3:
  1040.         (thh, tmm, tss) = tm
  1041.     else:
  1042.         return None
  1043.     
  1044.     try:
  1045.         yy = int(yy)
  1046.         dd = int(dd)
  1047.         thh = int(thh)
  1048.         tmm = int(tmm)
  1049.         tss = int(tss)
  1050.     except ValueError:
  1051.         return None
  1052.  
  1053.     tzoffset = None
  1054.     tz = tz.upper()
  1055.     if tz in _timezones:
  1056.         tzoffset = _timezones[tz]
  1057.     else:
  1058.         
  1059.         try:
  1060.             tzoffset = int(tz)
  1061.         except ValueError:
  1062.             pass
  1063.  
  1064.     if tzoffset:
  1065.         if tzoffset < 0:
  1066.             tzsign = -1
  1067.             tzoffset = -tzoffset
  1068.         else:
  1069.             tzsign = 1
  1070.         tzoffset = tzsign * ((tzoffset // 100) * 3600 + (tzoffset % 100) * 60)
  1071.     
  1072.     return (yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset)
  1073.  
  1074.  
  1075. def parsedate(data):
  1076.     '''Convert a time string to a time tuple.'''
  1077.     t = parsedate_tz(data)
  1078.     if t is None:
  1079.         return t
  1080.     
  1081.     return t[:9]
  1082.  
  1083.  
  1084. def mktime_tz(data):
  1085.     '''Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.'''
  1086.     if data[9] is None:
  1087.         return time.mktime(data[:8] + (-1,))
  1088.     else:
  1089.         t = time.mktime(data[:8] + (0,))
  1090.         return t - data[9] - time.timezone
  1091.  
  1092.  
  1093. def formatdate(timeval = None):
  1094.     """Returns time format preferred for Internet standards.
  1095.  
  1096.     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
  1097.  
  1098.     According to RFC 1123, day and month names must always be in
  1099.     English.  If not for that, this code could use strftime().  It
  1100.     can't because strftime() honors the locale and could generated
  1101.     non-English names.
  1102.     """
  1103.     if timeval is None:
  1104.         timeval = time.time()
  1105.     
  1106.     timeval = time.gmtime(timeval)
  1107.     return '%s, %02d %s %04d %02d:%02d:%02d GMT' % (('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[timeval[6]], timeval[2], ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[timeval[1] - 1], timeval[0], timeval[3], timeval[4], timeval[5])
  1108.  
  1109. if __name__ == '__main__':
  1110.     import sys
  1111.     import os
  1112.     file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
  1113.     if sys.argv[1:]:
  1114.         file = sys.argv[1]
  1115.     
  1116.     f = open(file, 'r')
  1117.     m = Message(f)
  1118.     print 'From:', m.getaddr('from')
  1119.     print 'To:', m.getaddrlist('to')
  1120.     print 'Subject:', m.getheader('subject')
  1121.     print 'Date:', m.getheader('date')
  1122.     date = m.getdate_tz('date')
  1123.     tz = date[-1]
  1124.     date = time.localtime(mktime_tz(date))
  1125.     if date:
  1126.         print 'ParsedDate:', time.asctime(date),
  1127.         hhmmss = tz
  1128.         (hhmm, ss) = divmod(hhmmss, 60)
  1129.         (hh, mm) = divmod(hhmm, 60)
  1130.         print '%+03d%02d' % (hh, mm),
  1131.         if ss:
  1132.             print '.%02d' % ss,
  1133.         
  1134.         print 
  1135.     else:
  1136.         print 'ParsedDate:', None
  1137.     m.rewindbody()
  1138.     n = 0
  1139.     while f.readline():
  1140.         n += 1
  1141.     print 'Lines:', n
  1142.     print '-' * 70
  1143.     print 'len =', len(m)
  1144.     if 'Date' in m:
  1145.         print 'Date =', m['Date']
  1146.     
  1147.     if 'X-Nonsense' in m:
  1148.         pass
  1149.     
  1150.     print 'keys =', m.keys()
  1151.     print 'values =', m.values()
  1152.     print 'items =', m.items()
  1153.  
  1154.